import axios from "axios";
import { Principal } from "./Principal";
import { verify } from "./Access";
import { Identity } from "../../config/nasty";

function getWebFiles(data: string[] | string | undefined) {
    if (data == null) return [];

    let isString = typeof data === 'string' ? true : false;

    let items = isString ? [data] : [...data];

    items = items || [];
    let list: any[] = [];


    items.forEach((t) => {
        let keyName = getFileKeyName(t);
        let url = `${Identity.BaseUrl}/System/File/Preview?key=${t}`
        let data = {
            uid: keyName.key,
            name: keyName.name,
            fileName: keyName.name,
            url: url,
            response: t,
            status: "done"
        };

        list.push(data);
    });

    return list;
}

function getServiceFiles(data: any | undefined, isArray: boolean = true) {
    let items = data?.fileList || [];
    let list: string[] = [];

    items.forEach((t: any) => {
        if (t.status == "done") {
            let url = t.response;
            list.push(url);
        }
    });

    if (isArray) {
        return list;
    } else {
        return list.length == 0 ? null : list[0];
    }

}

function getFileKeyName(str: string) {
    const firstUnderscoreIndex = str.indexOf('_');
    const result = {
        key: str.substring(0, firstUnderscoreIndex),
        name: str.substring(firstUnderscoreIndex + 1)
    }
    return result;
}

function toLowerCaseKeys(obj: any) {
    const newObj = {};
    Object.keys(obj).forEach(key => {
        newObj[key.toLowerCase()] = obj[key];
    });
    return newObj;
}

function getPreviewUrl(key: any, w: any = null, h: any = null, bucket: any = null) {
    if (key == null) return "";
    let url = `${Identity.BaseUrl}/System/File/Preview?key=${key}`
    if (w && h) url = `${url}&w=${w}&h=${h}`;
    if (bucket) url = `${url}&bucket=${bucket}`;
    return url;
}

const equal = (arr1: string[], arr2: string[]) => {
    if (arr1.length !== arr2.length) return false;

    return contains(arr1, arr1);
}

const contains = (arr1: string[], arr2: string[]) => {
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);

    // 检查每个元素是否都在另一个集合中
    return [...set1].every(item => set2.has(item));
}

function difference(arr1: string[], arr2: string[]) {
    const setB = new Set(arr2);
    return arr1.filter(item => !setB.has(item));
}

function remove(arr1: string[], arr2: string[]) {
    const setB = new Set(arr2);
    return arr1.filter(item => !setB.has(item));
}

const getFileListUIDs = (fileList: any[]) => {
    let uids: string[] = [];
    fileList.forEach((t) => {
        if (t.response) {
            let img = t.response as string;
            let uid = img.replace(`_${t.name}`, '');
            uids.push(uid);
        } else {
            uids.push(t.uid);
        }
    });

    return uids;
}

function filterByField(arr: any[], field: string) {
    const map = new Map();
    arr.forEach(item => {
        if (!map.has(item[field])) {
            map.set(item[field], item);
        }
    });
    return Array.from(map.values());
}

function downloadExport(key: string) {
    download(key, "Temp");
}

function download(key: string, bucket: string | null) {
    let api = `/System/File/Download?key=${encodeURIComponent(key)}`;
    if (bucket != null) api = `${api}&bucket=${bucket}`;
    api = `${Identity.BaseUrl}/${api}`;

    axios.get(api, {
        responseType: 'blob', // 关键：以二进制流接收
        headers: {
            "Authorization": `Bearer ${Principal.getToken()}`
        }
    }).then(response => {
        // 获取文件名（从响应头或自定义）
        let fileName = key;
        const disposition = response.headers['content-disposition'];
        if (disposition && disposition.indexOf('filename=') !== -1) {
            const match = disposition.match(/filename="?([^"]+)"?/);
            if (match && match[1]) {
                fileName = decodeURIComponent(match[1]);
            }
        }

        // 创建 blob 对象
        const url = window.URL.createObjectURL(new Blob([response.data]));
        // 创建 a 标签并触发下载
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName); // 设置下载文件名
        document.body.appendChild(link);
        link.click();
        // 清理
        link.remove();
        window.URL.revokeObjectURL(url);
    }).catch(() => {

    });
}

function _verify(roles: string[] = [], permissions: string[] = [], isUnion: boolean = false) {
    return verify(roles, permissions, isUnion);
}

function verifyClass(roles: string[] = [], permissions: string[] = [], isUnion: boolean = false) {
    let res = verify(roles, permissions, isUnion);
    if (res) {
        return "";
    } else {
        return "c-auth-no-access";
    }
}


export const util = {
    verify: _verify,
    verifyClass,
    downloadExport,
    download,
    getWebFiles,
    getServiceFiles,
    toLowerCaseKeys,
    getPreviewUrl,
    getFileListUIDs,
    equal,
    remove,
    contains,
    filterByField,
    difference
}